import {
  reactive,
  onMounted,
  defineComponent,
  toRefs,
  getCurrentInstance,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import requirementApi from "@/api/purchase/requirement-api";
import projectApi from "@/api/inwarehouse/project-api";
import goodsApi from "@/api/inwarehouse/goods-api";
import inventoryApi from "@/api/inwarehouse/inventory-api";
import ZlrtTable from "@/components/zlrt-table/table.vue";
import ZlrtSearch from "@/components/zlrt-search/search.vue";
import TableContext from "@/components/zlrt-table/table-context";
import requestApi from "@/api/purchase/request-api";
import orderChangeApi from "@/api/purchase/orderChange-api";
import goodsChange from "../request/goodsChange.vue";
import { exportExcel } from "@/utils/exprotExcel";

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch,
    goodsChange,
  },
  setup() {
    const statusOptions = [
      { value: "0", label: "新建" },
      { value: "99", label: "已完成" },
      { value: "100", label: "已同步" },
    ];

    const orderCtx = reactive(
      new TableContext(getCurrentInstance(), {
        title: "物料清单",
        api: requirementApi,
        columns: [
          { prop: "projectName", label: "项目", valueType: "slot" },
          { prop: "blueprintName", label: "图纸名称", valueType: "slot" },
          { prop: "num", label: "套数", slot: true, width: 80 },
          { prop: "operation", label: "操作", slot: true, width: 250 },
        ],

        other: {
          getStatus(val) {
            if (!val) {
              return "-";
            }
            return statusOptions.find((item) => {
              return item.value === val;
            }).label;
          },
          handleSkuChange(val: string, scope) {
            const obj = data.goodsOptions.find((item) => {
              return item.skuName === val;
            });
            const index = orderGoodsCtx.data.findIndex((item) => {
              return item.barCode === scope.row.barCode;
            });
            orderGoodsCtx.data.splice(index, 1, obj);
            data.goodsOptions = [{ ...obj }];
          },
          showEdit(row) {
            data.goodsOptions = [];
            orderGoodsCtx.data = [];
            orderCtx.showEdit(row).then((d) => {
              orderGoodsCtx.data = orderCtx.editData?.orderGoodsList;
            });
          },
          async getDetail(row) {
            data.orderChanggLoading = true;
            const params = { filter: { orderId: row.id } };
            const res = await orderChangeApi.list(params);
            data.orderChanggLoading = false;
            if (res.success) {
              data.orderChangeVisible = true;
              data.orderChangeList = res.data.records;
            }
          },
        },
      })
    );

    const orderGoodsCtx = reactive(
      new TableContext(getCurrentInstance(), {
        pageSize: 0,
        selection: false,
        columns: [
          { prop: "skuName", label: "物料名称", slot: true, width: 600 },
          { prop: "barCode", label: "物料编码", width: 150 },
          { prop: "specification", label: "规格型号" },
          { prop: "number", label: "数量", slot: true, width: 90 },
          { prop: "unit", label: "单位", width: 90 },
          { prop: "operation", label: "操作", slot: true, width: 150 },
        ],
      })
    );

    const getRowClassName = (item) => {
      const { row } = item;
      const goodsList = row.goodsList;
      if (goodsList && goodsList.length > 0) {
        const index = goodsList.findIndex((gol) => gol.needNumber > 0);
        if (index > -1) {
          return "tableRowClassName";
        }
      }
      return "";
    };

    const importCtx = reactive(
      new TableContext(getCurrentInstance(), {
        title: "物料清单",
        // searchLoading: false,
        pageSize: 0,
        selection: false,
        expand: true,
        defaultExpandAll: true,
        rowClassName: getRowClassName,
        columns: [
          // { prop: 'num', label: '序号' },
          { prop: "skuName", label: "物料名称", width: "300", sortable: true },
          { prop: "specification", label: "规格型号" },
          { prop: "total", label: "需求总数", width: "100" },
          { prop: "unit", label: "单位", width: "90" },
          { prop: "remark", label: "备注", width: "200" },
        ],
        rules: {
          projectName: [
            { required: true, message: "请选择项目", trigger: "change" },
          ],
        },

        other: {
          async getList(scope) {
            data.tempInventoryList = [];
            const res = await inventoryApi.list({
              filter: { barCode: scope.row.barCode },
            });
            const list = res.data.records;
            if (!list || list.length === 0) {
              return;
            }
            const arr = list.filter((item) => {
              return item.projectId && item.number > 0;
            });
            data.tempInventoryList = arr;
          },
          importMultiple: async (options) => {
            importCtx.editData = {};
            importCtx.importLoading = true;
            importCtx.data = [];
            const res = await requirementApi.uploadMultiple({
              file: options.file,
            });
            importCtx.importLoading = false;
            if (res.data && res.data.length > 0) {
              data.requirementList = res.data;
              const tempArr = [];
              data.requirementList.map((item) => {
                item["blueprintName"] = importCtx.other.getBlueprintName(
                  item.boxName
                );
                item["boxNum"] = importCtx.other.getBoxNum(
                  item["blueprintName"]
                );
                const lstOrder = item.lstOrder;
                lstOrder.map((lst) => {
                  const index = tempArr.findIndex((ta) => {
                    return (
                      importCtx.other.delSpace(lst.skuName) ===
                        importCtx.other.delSpace(ta.skuName) &&
                      importCtx.other.delSpace(lst.specification) ===
                        importCtx.other.delSpace(ta.specification) &&
                      importCtx.other.delSpace(lst.remark) ===
                        importCtx.other.delSpace(ta.remark) &&
                      importCtx.other.delSpace(lst.unit) ===
                        importCtx.other.delSpace(ta.unit)
                    );
                  });
                  if (index === -1) {
                    lst["total"] = lst.number * item["boxNum"];
                    tempArr.push(lst);
                  } else {
                    tempArr[index].total =
                      (tempArr[index].total * 1000 +
                        lst.number * item["boxNum"] * 1000) /
                      1000;
                  }
                });
              });
              importCtx.data = JSON.parse(JSON.stringify(tempArr));
              importCtx.editVisible = true;
              importCtx.data.map((item) => {
                item["searchSkuName"] = item["skuName"];
                item["searchSpecification"] = item["specification"];
              });
            }
            importCtx.importFiles = [];
          },
          delSpace(str) {
            if (!str) {
              return "";
            }
            if (str.indexOf(" ") > -1) {
              const temp = str.replaceAll(" ", "");
              return temp;
            }
            return str;
          },
          getBlueprintName(name) {
            if (!name) {
              return "";
            }
            const tempName = name.replace(/:/g, "：");
            const arr1 = tempName.split("柜号：");
            const arr2 = arr1[1].split("编号：");
            return arr2[0].trim();
          },
          getBoxNum(str) {
            if (!str) {
              return;
            }
            let arr = [];
            if (str.indexOf("\\") > -1) {
              arr = str.split("\\");
            } else {
              arr.push(str);
            }
            return arr.length;
          },
          handelProjectChange(val: string) {
            const obj = data.projectOptions.find((item) => {
              return item.name === val;
            });
            if (!obj) {
              return;
            }
            importCtx.editData.projectId = obj.id;
            importCtx.editData.projectName = obj.name;
            importCtx.editData.projectOriginalNo = obj.originalNo;
            // console.log('importCtx',importCtx)
          },
          submit: async () => {
            await importCtx.formRef.validate(async (validated) => {
              if (!validated) {
                document.getElementById("import-top").scrollIntoView();
                return;
              }
              if (!importCtx.editData.projectOriginalNo) {
                ElMessage.warning("项目没有合同号");
                return;
              }

              const index = importCtx.data.findIndex((imctx) => {
                const goodsList = imctx.goodsList;
                return importCtx.other.getFlag(goodsList);
              });
              // if (index > -1) {
              //   ElMessage.warning(
              //     '请检查"' + importCtx.data[index].skuName + '"需求数量'
              //   );
              //   return;
              // }

              importCtx.data.map((item) => {
                const arr = item.goodsList?.filter(
                  (gl) => gl.needNumber && gl.needNumber > 0
                );
                if (arr && arr.length > 0) {
                  const goodsList = JSON.parse(JSON.stringify(arr));
                  const lstArr = [];
                  data.requirementList.map((rml) => {
                    const boxNum = rml.boxNum;
                    const lstOrder = rml.lstOrder;
                    lstOrder.map((lst) => {
                      if (
                        importCtx.other.delSpace(lst.skuName) ===
                          importCtx.other.delSpace(item.skuName) &&
                        importCtx.other.delSpace(lst.specification) ===
                          importCtx.other.delSpace(item.specification) &&
                        importCtx.other.delSpace(lst.remark) ===
                          importCtx.other.delSpace(item.remark) &&
                        importCtx.other.delSpace(lst.unit) ===
                          importCtx.other.delSpace(item.unit)
                      ) {
                        lst["boxNum"] = boxNum;
                        lstArr.push(lst);
                      }
                    });
                  });
                  lstArr.map((la) => {
                    goodsList.map((gl) => {
                      gl["isCheck"] = true;
                      if (goodsList.length > 0) {
                        gl["numberCheck"] = la.number;
                      } else {
                        gl["numberCheck"] = la.number * la.boxNum;
                      }
                      gl["number"] = la.number / goodsList.length;
                      gl["goodsId"] = gl["id"];
                    });
                    la.goodsList = goodsList;
                  });
                }
              });

              ElMessageBox.confirm(
                `确认当前已选数据生成物料清单？`,
                "温馨提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                  draggable: true,
                }
              )
                .then(async () => {
                  const paramsArr = [];
                  const requestGoodsList = [];
                  const blueprintArr = [];
                  data.requirementList.map((rml) => {
                    blueprintArr.push(rml.blueprintName);
                    const lstOrder = rml.lstOrder;
                    let orderGoodsList = [];
                    lstOrder.map((lo) => {
                      if (lo.goodsList && lo.goodsList.length > 0) {
                        const ogl = JSON.parse(JSON.stringify(lo.goodsList));
                        const { projectId, projectName, projectOriginalNo } =
                          importCtx.editData;
                        ogl.map((gl) => {
                          gl["projectId"] = projectId;
                          gl["projectName"] = projectName;
                          gl["projectOriginalNo"] = projectOriginalNo;
                          gl["reqSkuName"] = lo.skuName;
                          gl["reqSpecification"] = lo.specification;
                          gl["reqRemark"] = lo.remark;
                          gl["reqNumber"] = lo.number;
                          delete gl["id"];
                          delete gl["needNumber"];
                          orderGoodsList.push(gl);
                        });
                      }
                    });
                    if (orderGoodsList && orderGoodsList.length > 0) {
                      const arr = [];
                      orderGoodsList.map((ogl) => {
                        const index = arr.findIndex((ar) => {
                          return ar.barCode === ogl.barCode;
                        });
                        if (index === -1) {
                          arr.push(ogl);
                        } else {
                          arr[index].number =
                            (arr[index].number * 1000 + ogl.number * 1000) /
                            1000;
                        }
                        const _index = requestGoodsList.findIndex((rgl) => {
                          return rgl.barCode === ogl.barCode;
                        });
                        if (_index === -1) {
                          requestGoodsList.push(ogl);
                        }
                      });
                      const requirementParams = {
                        ...importCtx.editData,
                        blueprintName: rml.blueprintName,
                        orderGoodsList: arr,
                      };
                      paramsArr.push(requirementParams);
                    }
                  });
                  paramsArr?.map((params, index) => {
                    data.finishLoading = true;
                    requirementApi.batchSave(params).then((res) => {
                      if (res.success && index === paramsArr.length - 1) {
                        data.finishLoading = false;
                        orderCtx.loadData();
                        ElMessage.success("新增成功");
                        importCtx.editVisible = false;
                      }
                    });
                  });

                  if (requestGoodsList.length > 0) {
                    const tempArr = [];
                    requestGoodsList.map((rgl) => {
                      const obj = JSON.parse(JSON.stringify(rgl));
                      if (obj["requestNumber"] > 0) {
                        obj["number"] = obj["requestNumber"];
                        delete obj["requestNumber"];
                        tempArr.push(obj);
                      }
                    });
                    if (tempArr.length > 0) {
                      const requestParams = {
                        ...importCtx.editData,
                        blueprintName: JSON.stringify(blueprintArr),
                        status: "0",
                        date: new Date(),
                        orderGoodsList: tempArr,
                      };
                      requestApi.save(requestParams);
                    }
                  }
                })
                .catch();
            });
          },
          searchSku: async (row) => {
            importCtx.searchLoading = true;
            const res = await goodsApi.list({
              current: 1,
              size: 30,
              otherFilter: { specification: row.searchSpecification },
            });
            importCtx.searchLoading = false;
            if (res.success) {
              row.goodsList = res.data.records;
            }
          },
          getData(data) {
            if (!data || data.length === 0) {
              return [];
            }
            // console.log('importCtx.editData',importCtx)
            return data;
          },
          addGoodList(data){
            return importCtx.data.push({});
          },
          getFlag(data) {
            if (!data || data.length === 0) {
              return true;
            }
            let flag = true;
            data.map((item) => {
              if (item.needNumber) {
                flag = false;
              }
            });
            return flag;
          },
          exportGoodsList() {
            const { projectName } = importCtx.editData;
            exportExcel({
              column: [
                { label: "物料名称", name: "skuName" },
                { label: "规格型号", name: "specification" },
                { label: "数量", name: "total" },
                { label: "单位", name: "unit" },
                { label: "备注", name: "remark" },
              ],
              data: importCtx.data,
              filename: projectName + "-物料清单",
              autoWidth: true,
              format: "xlsx",
            });
          },
        },
      })
    );

    const getProjectList = async () => {
      const params = { filter: { disabled: 2 } };
      const res = await projectApi.list(params);
      data.projectOptions = res.data.records;
    };

    const getGoodsList = async (val: string) => {
      data.loading = true;
      const params = { otherFilter: { skuName: val } };
      const res = await goodsApi.list(params);
      data.loading = false;
      data.goodsOptions = res.data.records;
    };

    const formatDate = (date) => {
      if (!date) {
        return "-";
      }
      return date.substring(0, 10) + " " + date.substring(11, 19);
    };

    const addRemark = async (prop, scope) => {
      const { row } = prop;
      const { goodsList, skuName } = scope.row;
      const tempArr = goodsList.filter((gol) => gol.requestNumber > 0);
      if (!tempArr || tempArr.length === 0) {
        ElMessage.warning("请检查“" + skuName + '"请购数量');
        return;
      }
      const res = await inventoryApi.list({ filter: { barCode: row.barCode } });
      const inventoryList = res.data.records;
      let temprRemark = row.skuName + "库存总数:" + row.number + "；";
      inventoryList.map((il) => {
        if (il.projectId) {
          temprRemark += `${il.projectName}库存数量:${il.number}；`;
        }
      });
      tempArr.map((ta) => {
        let remark = ta.remark || "";
        remark += temprRemark;
        Object.assign(ta, { remark });
      });
    };

    const searchObj = {
      dialogVisible: false,
    };
    const selectedGood = {};
    const changeGoods = (row) => {
      Object.assign(selectedGood, {
        ...row,
      });
      Object.assign(data.searchObj, {
        ...row,
        dialogVisible: true,
      });
    };

    const delGoods = (row) => {
      const { id } = row;
      const index = orderCtx.editData.orderGoodsList.findIndex((item) => {
        return item.id === id;
      });
      orderCtx.editData.orderGoodsList.splice(index, 1);
    };

    const closeDialog = () => {
      data.searchObj = {
        dialogVisible: false,
      };
      // Object.assign(data.searchObj, {
      //   dialogVisible: false
      // })
    };

    const changedGood = async (data) => {
      ElMessageBox.confirm(`确认选择当前物料？`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(async () => {
          const oldBarCode = selectedGood["barCode"];
          const goodsId = searchObj["goodsId"];
          const { barCode, skuName } = data;
          const params = {
            projectId: orderCtx.editData.projectId,
            goodsId,
            oldBarCode,
            newBarCode: barCode,
            skuName,
          };
          const res = await projectApi.changeBarCode(params);
          if (res.success) {
            ElMessage.success("修改成功");
            getDetail(orderCtx.editData.id);
            closeDialog();
          }
        })
        .catch();
    };

    const getDetail = async (id) => {
      const res = await requirementApi.detail(id);
      if (res.success) {
        const { orderGoodsList } = res.data;
        data.orderGoodsCtx.data = [].concat(orderGoodsList);
      }
    };

    const addChange = () =>{
      data.addRequest = true
      // console.log('data.addRequest',data.addRequest)
    }

    const data = reactive({
      listData:[],
      orderCtx,
      orderGoodsCtx,
      importCtx,
      projectOptions: [],
      loading: false,
      goodsOptions: [],
      requirementList: [],
      finishLoading: false,
      tempInventoryList: [],
      orderChangeVisible: false,
      orderChanggLoading: false,
      orderChangeList: [],
      dialogVisible: false,
      addRequest:false,
      searchObj,
      getGoodsList,
      formatDate,
      addRemark,
      changeGoods,
      closeDialog,
      delGoods,
      changedGood,
      addChange
    });

    // init
    onMounted(() => {
      getProjectList();
      orderCtx.loadData();
    });

    return {
      ...toRefs(data),
    };
  },
});
